from .base import BaseModel, db
import uuid
from datetime import datetime
from .user_models import UUIDString

class Message(BaseModel):
    __tablename__ = 'messages'
    
    id = db.Column(UUIDString, primary_key=True, default=lambda: str(uuid.uuid4()))
    sender_id = db.Column(UUIDString, db.ForeignKey('users.id'), nullable=False)
    receiver_id = db.Column(UUIDString, db.ForeignKey('users.id'), nullable=False)
    
    # 消息内容（加密存储）
    encrypted_content = db.Column(db.LargeBinary, nullable=False)
    message_key = db.Column(db.LargeBinary, nullable=False)  # 加密的消息密钥
    nonce = db.Column(db.String(32), nullable=False)  # AES-GCM nonce
    tag = db.Column(db.String(32), nullable=False)  # AES-GCM tag
    
    # 消息类型：text, image, voice, file
    message_type = db.Column(db.String(20), default='text')
    file_ext = db.Column(db.String(10))  # 文件扩展名（如jpg, mp3等）
    
    # 消息状态
    is_read = db.Column(db.Boolean, default=False)
    deleted = db.Column(db.Boolean, default=False)
    deleted_at = db.Column(db.DateTime)
    
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)
    
    # 关联关系
    sender = db.relationship('User', foreign_keys=[sender_id], backref='sent_messages')
    receiver = db.relationship('User', foreign_keys=[receiver_id], backref='received_messages')